package com.learn.algorithm_1290;

import com.dataconsruct.ListNode;

/**
 * 二进制链表转十进制整数
 * https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer/
 */
public class ListNodeToInt {

    /**
     * 输入：head = [1,0,1]
     * 输出：5
     */
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode next = new ListNode(0);
        head.next = next;
        next.next = new ListNode(1);

        System.out.println(new ListNodeToInt().getDecimalValue(head));
    }

    public int getDecimalValue(ListNode head) {
        // 不改变原来的head
        ListNode cur = head;
        int sum = 0;
        while (cur != null) {
            // 已累加数要 * 2
            sum *= 2;
            sum += cur.val;
            // 下一轮
            cur = cur.next;
        }
        return sum;
    }

}
